<?php
namespace Common\Models;
use Common\BaseModel;
class Messages extends BaseModel
{
	public $res;
	public $expire;
	public function getSource()
    {
        return "f_messages";
    }

    public function list_message($user_id,$data=[]){
        $conditions = "user_id = {$user_id}";
        $size  = isset($data['page_size']) ? $data['page_size'] : 10;
        $page  = isset($data['page']) ? ($data['page'] - 1) * $size : 0;
        if(isset($data['is_read'])){
            if($data['is_read'] == 0){
                $conditions .= ' AND is_read=0';
            }
            if($data['is_read'] == 1){
                $conditions .= 'AND is_read=1';
            }
        }
        $user_list = $this->find(
            array(
                $conditions,
                'columns'=>'id,title,content as abstract,created_at,is_read',
                'order'=>'id DESC',
                "limit"=>$size,
                "offset"=>$page,
            )
        );

        foreach($user_list as $k=>$v){  //消息设置为已读
            $this->is_read_save($v->id);
        }

        return $user_list->toarray();
    }


    //获取没有读过的条数
    public function mess_count($user_id,$data=[]){
        $conditions = "user_id = {$user_id}";
        if(isset($data['is_read'])){
            if($data['is_read'] == 0){
                $conditions .= ' AND is_read=0';
            }
            if($data['is_read'] == 1){
                $conditions .= 'AND is_read=1';
            }
        }
        $count = $this::count(
            array(
                $conditions,
            )
        );
        return $count;
    }


    /**
     * 保存
     */
    public function save_params($user_id,$tips,$title=''){
        $this->user_id=$user_id;
        $this->title=$title;
        $this->content=$tips;
        $this->created_at=date('Y-m-d H:i:s');
        $this->updated_at=date('Y-m-d H:i:s');
        $this->is_read=0;
        $this->save();
    }


    /**
     * @param $user_id
     * 用户读取公告
     */
    public function is_read_save($id){
        $message_one=$this->findFirstById($id);
        $message_one->is_read=1;
        $message_one->save();
    }

}
